package com.ynding.cloud.auth.server.admin.job;

import cn.hutool.core.collection.CollectionUtil;
import com.ynding.cloud.auth.api.admin.domain.MenuDO;
import com.ynding.cloud.auth.api.admin.entity.Role;
import com.ynding.cloud.auth.server.admin.service.IMenuService;
import com.ynding.cloud.common.model.bo.AuthConstants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p> 初始化 菜单-角色 值入redis</p>
 *
 * @author ynding
 * @version 2021/7/26
 **/
@Component
@AllArgsConstructor
@Slf4j
public class InitResourceRolesCacheRunner implements CommandLineRunner {

    private final RedisTemplate redisTemplate;
    private final IMenuService menuService;

    @Override
    public void run(String... args) throws Exception {
        log.info("InitResourceRolesCacheRunner run");
        redisTemplate.delete(AuthConstants.RESOURCE_ROLES_KEY);
        List<MenuDO> menus = menuService.findAll();
        Map<String, List<String>> resourceRolesMap = new TreeMap<>();
        Optional.ofNullable(menus).orElse(new ArrayList<>()).forEach(menu -> {
            List<String> roles = Optional.ofNullable(menu.getRoles()).orElse(new ArrayList<>())
                    .stream().map(Role::getName)
                    .collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(roles)) {
                resourceRolesMap.put(menu.getUrl(), roles);
            }
            redisTemplate.opsForHash().putAll(AuthConstants.RESOURCE_ROLES_KEY, resourceRolesMap);
        });
    }
}
